﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Liquid.Windows.Commands {
	public sealed class CommandCollection : Collection<Command> {
		//: KeyedCollection<string, Command>
		//protected override string GetKeyForItem(Command item) {
		//    return item.Name;
		//}

		CommandSet owner;
		public CommandCollection(CommandSet owner) {
			this.owner = owner;
		}
		private void ChangeOwner(Command item, CommandSet value) {
			var e = new CommandEventArgs(item);
			if (item.CommandSet != default(CommandSet))
				owner.OnCommandRemoved(e);
			if (value != default(CommandSet))
				owner.OnCommandAdded(e);
			item.CommandSet = value;
		}
		protected override void SetItem(int index, Command item) {
			base.SetItem(index, item);
			ChangeOwner(item, owner);
		}
		protected override void ClearItems() {
			var copy = this.ToArray();
			base.ClearItems();
			foreach (Command item in copy)
				ChangeOwner(item, null);
		}
		protected override void InsertItem(int index, Command item) {
			if (!this.Contains(item)) {
				base.InsertItem(index, item);
				ChangeOwner(item, null);
			}
		}
		protected override void RemoveItem(int index) {
			base.RemoveItem(index);
			ChangeOwner(this[index], null);
		}
	}
}
